const TOKEN_KEY = 'geek-mobile' // 用户 Token 的本地缓存键名
const CHANNEL_KEY = 'geek-channels' // 频道
const SEARCH_KEY = 'geek-keywordSearch' // 搜索关键

type Token = {
  token: string
  refresh_token: string
}

type Channels = {
  id: number
  name: string
}

/**
 * 从本地缓存中获取 Token 信息
 */

export const getTokenInfo = () => {
  // JSON.parse()参数必须是string
  // localStorage.getItem()返回的结果类型是string | null

  return JSON.parse(localStorage.getItem(TOKEN_KEY) || '{}')
  // 断言解决
  // return JSON.parse(localStorage.getItem(TOKEN_KEY) as string) || {} //类型断言
  // return JSON.parse(localStorage.getItem(TOKEN_KEY)!) || {} //非空断言
}

/**
 * 将 Token 信息存入缓存
 * @param {Object} tokenInfo 从后端获取到的 Token 信息
 */

export const setTokenInfo = (tokenInfo: Token) => {
  localStorage.setItem(TOKEN_KEY, JSON.stringify(tokenInfo))
}

/**
 * 删除本地缓存中的 Token 信息
 */
export const removeTokenInfo = () => {
  localStorage.removeItem(TOKEN_KEY)
}

/**
 * 判断本地缓存中是否存在 Token 信息
 */
export const hasToken = () => {
  return !!getTokenInfo().token
}

// 存储频道到本地
export const setLocalChannels = (channels: Channels[]) => {
  localStorage.setItem(CHANNEL_KEY, JSON.stringify(channels))
}

// 获取本地存储的频道
export const getLocalChannels = (): Channels[] => {
  return JSON.parse(localStorage.getItem(CHANNEL_KEY)!)
}

// 删除本地频道数据
export const removeLocalChannels = () => {
  localStorage.removeItem(CHANNEL_KEY)
}

// 所搜历史记录
export const getLocalHistory = (): string[] => {
  return JSON.parse(localStorage.getItem(SEARCH_KEY)!) || []
}

export const setLoaclHistory = (histories: string[]) => {
  localStorage.setItem(SEARCH_KEY, JSON.stringify(histories))
}

// 清除历史记录
export const removeLocalHistories = () => {
  localStorage.removeItem(SEARCH_KEY)
}
